<script setup lang="ts">
import VueEcharts from 'vue-echarts'
import { uniqBy } from 'lodash-es'
import type { VChartInstance } from '@/types'
import { useChartAutoResize } from '@/mixins/MixinChartAutoResize'

interface Item {
  name: string
  value: number
  subList: Item[]
}

const props = defineProps<{
  data: Item[]
}>()

const designStore = useDesignStore()
const option = computed(() => {
  const data = uniqBy(getNameRecursively(props.data, []), 'name')
  const links = getLinksRecursively(props.data, [])
  // console.log(data, links)
  return {
    title: {
      text: `企业碳排分流图`,
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
      },
      left: 20,
      top: 20,
    },
    tooltip: {
      show: false,
      trigger: 'item',
      triggerOn: 'mousemove',
      formatter(params: any) {
        return `${params.name}: ${Number.parseFloat(params.value).toFixed(2)}` // 保留两位小数
      },
    },
    series: [
      {
        type: 'sankey',
        layout: 'none',
        draggable: true,
        left: 140,
        right: 140,
        bottom: 60,
        top: 60,
        emphasis: {},
        data,
        links,
        lineStyle: {
          // color: 'gradient',
          color: '#87f7cf',
          opacity: 0.1,
          curveness: 0.5,
        },
      },
    ],
  }
})

function getNameRecursively(data: Item[], result: { name: string }[]): { name: string }[] {
  for (const item of data) {
    result.push({ name: `${item.name}` })
    if (item.subList && item.subList.length > 0) {
      getNameRecursively(item.subList, result)
    }
  }
  return result
}

function getLinksRecursively(data: Item[], result: { source: string, target: string, value: number }[]): { source: string, target: string, value: number }[] {
  // 总共四级，
  // 第一级是source，第二级是target，然后
  // 第二级是soucce，第三级是target，然后
  // 第三级是source，第四级是target，结束
  for (const item of data) {
    if (item.subList && item.subList.length > 0) {
      for (const child of item.subList) {
        result.push({
          source: item.name,
          target: child.name,
          value: child.value,
        })
      }
      getLinksRecursively(item.subList, result)
    }
  }
  return result
}

const chartRef = ref<VChartInstance>()

useChartAutoResize(chartRef)
</script>

<template>
  <VueEcharts ref="chartRef" :option="option" :theme="designStore.theme" />
</template>
